<?php
/*
 * @project CreativeFramework
 * @version <#RELEASE_VERSION#>
 * @license GNU Lesser General Public License
 * @author Jimmie Lin
 */

class Login extends CF_Controller {
	function __construct() {
		global $Lang;
		$this->title = $Lang->getFormattedKey("global.user.login");
		$this->desc = "";
	}
	
	function Index() {
		global $Views, $Models, $DB, $Encryption, $UI, $Lang, $Hooks;
		if(isset($_SESSION["cf_uid"])) {
			$Hooks->run_hooks("login_already_logged_before");
			$Views->Load("already_logged_in");
			$Hooks->run_hooks("login_already_logged_after");
		}
		else {
			if(isset($_POST['username'], $_POST['password'])) {
				$Users_model = $Models->Load("users_model");
				$rt = $Users_model->retrieve("singleuname", $_POST['username']);
				if($rt) {
					if($rt['password'] === $Encryption->Encrypt($_POST['password'])) {
						$UI->message($Lang->getFormattedKey("global.user.login.success"), "success");
						$UI->redirect("/index.php");
						$_SESSION["cf_uid"] = $rt['id'];
						$_SESSION["cf_passhash"] = $rt['password'];
					}
					else {
						// Password does not match
						$UI->message($Lang->getFormattedKey("global.user.login.fail.pw"), "error");
						$Views->Load("login_form");
					}
				}
				else{
					// Username not found
					$UI->message($Lang->getFormattedKey("global.user.login.fail.un"), "error");
					$Views->Load("login_form");
				}
			} // end if(POST)
			else {
				// Show form :)
				$Views->Load("login_form");
			}
		}
	}
}
